using Infrastructure;
using Infrastructure.Attribute;
using System.Text.Json;
using ZR.Model.System;
using ZR.Model.System.Dto;
using ZR.ServiceCore.Services.IService;

namespace ZR.ServiceCore.Services
{
    /// <summary>
    /// 激光雷达状态服务实现
    /// </summary>
    [AppService(ServiceType = typeof(IWindLidarStatusService), ServiceLifetime = LifeTime.Transient)]
    public class WindLidarStatusService : IWindLidarStatusService
    {
        private readonly HttpClient _httpClient;
        private const string API_URL = "http://leida.vip.cpolar.cn/api/windlidar/status";

        public WindLidarStatusService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        /// <summary>
        /// 获取激光雷达状态（异步方法）
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        public async Task<WindLidarStatusResultDto> GetWindLidarStatusAsync(WindLidarStatusRequestDto request = null)
        {
            try
            {
                // 设置默认参数
                if (request == null)
                {
                    request = new WindLidarStatusRequestDto
                    {
                        CommandType = "status",
                        CommandData = null
                    };
                }

                // 构建请求URL，添加参数
                var url = $"{API_URL}?commandtype={request.CommandType}&commanddata={request.CommandData}";
                
                Console.WriteLine($"激光雷达状态查询 - 开始调用API: {url}");
                
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                
                var jsonContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"激光雷达状态查询 - API响应: {jsonContent}");
                
                var apiResponse = System.Text.Json.JsonSerializer.Deserialize<WindLidarStatusResponseDto>(jsonContent, new System.Text.Json.JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (apiResponse?.Data == null)
                {
                    throw new Exception("API返回数据为空");
                }

                var result = ConvertToResultDto(apiResponse.Data);
                Console.WriteLine($"激光雷达状态查询 - 转换完成，状态: {result.StatusDescription}");
                
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"激光雷达状态查询 - 出错: {ex.Message}");
                throw new Exception($"获取激光雷达状态失败: {ex.Message}", ex);
            }
        }


        /// <summary>
        /// 转换为结果DTO
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <returns></returns>
        private WindLidarStatusResultDto ConvertToResultDto(WindLidarStatus data)
        {
            return new WindLidarStatusResultDto
            {
                Azimuth = data.Azimuth,
                CardStatus = data.CardStatus,
                Elevation = data.Elevation,
                LaserTemp = data.LaserTemp,
                LaserStatus = data.LaserStatus,
                LidarInRh = data.LidarInRh,
                LidarInRt = data.LidarInRt,
                LidarStatus = data.LidarStatus,
                Storage = data.Storage,
                QueryTime = DateTime.Now,
                StatusDescription = GetLidarStatusDescription(data.LidarStatus),
                LaserStatusDescription = GetLaserStatusDescription(data.LaserStatus),
                CardStatusDescription = GetCardStatusDescription(data.CardStatus)
            };
        }

        /// <summary>
        /// 获取激光雷达状态描述
        /// </summary>
        /// <param name="status">状态值</param>
        /// <returns></returns>
        private string GetLidarStatusDescription(int status)
        {
            return status switch
            {
                0 => "离线",
                1 => "在线",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取激光器状态描述
        /// </summary>
        /// <param name="status">状态值</param>
        /// <returns></returns>
        private string GetLaserStatusDescription(int status)
        {
            return status switch
            {
                0 => "正常",
                1 => "异常",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取卡片状态描述
        /// </summary>
        /// <param name="status">状态值</param>
        /// <returns></returns>
        private string GetCardStatusDescription(int status)
        {
            return status switch
            {
                0 => "正常",
                1 => "异常",
                _ => "未知状态"
            };
        }
    }
}
